package com.killer.rpc;

import com.killer.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 自定义rpc编码器，将传输进来的rpcRequest对象编码成字节数组
 */
public class RpcEncoder extends MessageToByteEncoder<RpcRequest> {

    private Serializer serializer;

    public RpcEncoder(Serializer serializer){
        this.serializer=serializer;
    }

    protected void encode(ChannelHandlerContext ctx, RpcRequest msg, ByteBuf out) throws Exception {
        byte[] bytes=serializer.serialize(msg);
        //写入消息长度
        out.writeInt(bytes.length);
        //写入消息
        out.writeBytes(bytes);
    }
}
